<?php

class ReceiveAddrController extends CommonController {
	
	private $model;
	public function __init() {
		//判断是否登陆
		parent::__init();
		$this -> model = K('ReceiveAddr');
		if (session('?uid') === FALSE || session('?username') === FALSE) {
			$this -> success('您还没有登陆呢!', U('Login/index'));
		}

	}
	
	
	
	/**
	 * 编辑收货地址
	 */
	 public function ajaxEditAddr(){
	 	if(!IS_AJAX) $this->error('非法请求');
		$reid = Q('post.reid',0,'intval');
		//如果为0那表示是用户中心的修改地址  如果为1那么就是提交订单的模板
		$ds = Q('post.ds',0,'intval');
		$currentAddr = $this->model->takeAddr($reid);
		$currentAddr['re_addarea'] = rtrim($currentAddr['re_addarea'],',');
		$currentAddr['re_addarea'] = explode(',',$currentAddr['re_addarea']);
		//返回当前收货地址的地区数组
		$citys = K('City')->getCityDist($currentAddr['re_addarea']);
		$this->assign('citys',$citys);
		$this->assign('currentaddr',$currentAddr);
		if(!$ds){
			$this->ajax($this->display(MODULE_VIEW_PATH.'/UserInfo/ajaxEditAddr',-1,null,'text/html',false));	
		}else{
			$this->ajax($this->display(MODULE_VIEW_PATH.'/Cart/ajaxAddr',-1,null,'text/html',false));
		}
		
		
	 }
	/**
	 * 当回用户收货地址
	 */
	 public function addAddr(){
	 	//如果添加成功返回那条添加成功的收货地址
	 	$data = $this->model->addAddrUser();
		if($data){
			$this->ajax(array('message'=>'添加成功','data'=>$data,'status'=>1));
		}else{
			$this->ajax(array('message'=>$this->model->error,'status'=>0));
		}
	 }
	
	
	
	/**
	 * 删除收货地址方法
	 */
	public function del(){
		if(IS_AJAX){
			$reid = Q('post.reid');
			if($this->model->delete(array('reid'=>$reid))){
				$this->ajax(array('message'=>'删除成功','status'=>1));
			}else{
				$this->ajax(array('message'=>'删除失败','status'=>0));
			}	
		}else{
			$this->error('非法请求');
		}			
	}
	
	/**
	 * 用户中心设置默认地址
	 */
	 public function defaultAddr(){
	 	if(!session('?uid')){
	 		$this->error('请您先登陆');
	 	}
		if(!IS_AJAX) $this->error('非法操作');
	 	//获得当前收货地址的ID	
	 	$reid = Q('get.reid',0,'intval');
		//获得当前用户id
		$uid = session('uid');
		//当前这条收货地址
		$currentAddr = $this->model->where("reid={$reid} AND uid={$uid}")->find();
		//判断不前收货地址是不是这个用户的
		if(!$currentAddr){
			$this->error('对不起找不到这条收货地址');
		}			
		//先将其他的地址设置为非默认
		if($this->model->where("uid={$uid}")->update(array('is_default'=>0)) && $this->model->where("reid={$reid} AND uid={$uid}")->update(array('is_default'=>1))){
			$this->ajax(array('message'=>'设置默认地址成功','status'=>1));	
		}else{
			$this->ajax(array('message'=>'设置默认地址失败','status'=>0));
		}

	 }
	
	/**
	 * 修改当前收货地址
	 */
	 public function subEdit(){
	 	
	 	$data = $this->model->ajaxEditAddr();
	 	if($data){
	 		$this->ajax(array('data'=>$data,'message'=>'修改成功','status'=>1));
	 	}else{
	 		$this->ajax(array('message'=>$this->model->error,'status'=>0));
	 	}
		
	 }
	

}
